import React, { Suspense, useState, useEffect, useRef } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls, Environment } from "@react-three/drei";
import * as THREE from "three";
import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader";
// 导入多个模型
import actor1ply from "../asserts/actor1.ply";
import actor2ply from "../asserts/actor2.ply";
import actor3ply from "../asserts/actor3.ply";
import actor4ply from "../asserts/actor4.ply";
import actor5ply from "../asserts/actor5.ply";

function PlyModel({ url }) {
  const [model, setModel] = useState(null);

  useEffect(() => {
    const loader = new PLYLoader();
    loader.load(url, (geometry) => {
      geometry.computeVertexNormals(); // 计算顶点法线以获得更好的光照效果
      const material = new THREE.MeshStandardMaterial({ color: "royalblue" });
      const mesh = new THREE.Mesh(geometry, material);
      setModel(mesh);
    });
  }, [url]);

  const scaleSize = 5; // 定义放大倍数
  return model ? (
    <primitive
      object={model}
      scale={new THREE.Vector3(scaleSize, scaleSize, scaleSize)}
    />
  ) : null;
}

function PlyDemo1() {
  // 用数组存储所有的模型文件路径
  const models = [actor1ply, actor2ply, actor3ply, actor4ply, actor5ply];
  const [currentIndex, setCurrentIndex] = useState(0);
  const timeoutRef = useRef(null);

  useEffect(() => {
    // 设置定时器来循环模型
    timeoutRef.current = setInterval(() => {
      setCurrentIndex((prevIndex) => (prevIndex + 1) % models.length);
    }, 1000); // 每秒切换模型

    return () => {
      if (timeoutRef.current) {
        clearInterval(timeoutRef.current);
      }
    };
  }, [models.length]);

  return (
    <Canvas
      camera={{ position: new THREE.Vector3(2, 2, 2), fov: 50 }}
      style={{ width: "100vw", height: "100vh" }}
    >
      <Suspense fallback={null}>
        <ambientLight intensity={0.5} />
        <spotLight
          position={[5, 5, 5]}
          angle={0.3}
          intensity={2}
          penumbra={1}
        />
        <PlyModel url={models[currentIndex]} />
        <OrbitControls />
      </Suspense>
    </Canvas>
  );
}

export default PlyDemo1;
